import re
from flask import Blueprint, request, jsonify
from sqlalchemy import or_
from app.models.book import Book
from app.libs.error_code import NotFound, ClientPostError
from app.validators.forms import BookSearchForm
from app.libs.helper import is_isbn_or_key
from app.libs.books_result import BooksResult

api = Blueprint('book', __name__, url_prefix='/book')


@api.route('/search', methods=['GET'])
def search():
    form = BookSearchForm(request.args)
    if form.validate():
        key = form.key.data
        count = form.count.data
        start = form.start.data
        isbn_or_key = is_isbn_or_key(key)
        if isbn_or_key == 'key':
            key = '%' + key + '%'
            books = Book.query.filter(
                or_(Book.title.like(key), Book.publisher.like(key), Book.author.like(key))
            ).all()
        # 在严格意义上的restful不讲究资源的调用，有就会输出
        # 但是在正式的业务开发时，去掉一些字段就能省去很多的服务器带宽的消耗
        # 如何去掉book的一些字段呢？  1.遍历book的字段然后去掉  2.view_model去修改
        # 或者
            if books:
                bookresult = BooksResult(books, count, start)
                return bookresult.to_json()
            else:
                raise NotFound()


@api.route('/isbn/<int:isbn>')
def search_by_isbn(isbn):
    books = Book.query.filter_by(isbn=isbn).all()
    if books:
        return jsonify(books)
    else:
        raise NotFound()


@api.before_request
def before_user():
    if request.path == "/v1/book/search":    # 登录有关的不用拦截
        return None
    if '/v1/book/isbn' in request.path:
        isbn = request.path.replace('/v1/book/isbn/', '')
        if len(isbn) == 13 and isbn.isdigit():
            return None
        raise ClientPostError()
    if request.path.startswith("/static"):    # 静态文件也不需要拦截
        return None
    if request.path.startswith("/api"):    # api接口相关的也不要拦截
        return None
    else:
        raise ClientPostError()
